#!/usr/bin/env python
# -*- coding: utf-8 -*- 

#Kiwi Bot
#Make by @nge1nCorsic4 in 2011
#Modified by @nge1nCorsic4 in 2012
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License along
#with this program; if not, write to the Free Software Foundation, Inc.,
#51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import kiwi, kiwi.config
import sqlite3
from os.path import isfile

class bd:
	def __init__(self):
		BDfile = kiwi.getPath(kiwi.config.configuration().kiwi.adminfile)
		if not isfile(BDfile):
			f = file(BDfile,'w')
			f.close()
		self.File = BDfile
	def Connect(self):
		conn = sqlite3.connect(self.File)
		conn.row_factory = sqlite3.Row
		conn.text_factory = sqlite3.OptimizedUnicode
		return conn
	def Create(self,table,arguments):
		connect = self.Connect()
		c = connect.cursor()
		create = "CREATE TABLE IF NOT EXISTS %s (%s)"%(table,arguments)
		# print create
		c.execute(create)
		connect.commit()
		c.close()
	def Insert(self,table,values):
		connect = self.Connect()
		c = connect.cursor()
		val = ''
		for a in values:
			val += '?,'
		val = val[:-1]
		insert = "INSERT INTO %s VALUES (%s)"%(table,val)
		# print insert, values
		c.execute(insert,values)
		connect.commit()
		c.close()
	def Update(self,table,guid,values):
		connect = self.Connect()
		c = connect.cursor()
		for a in values:
			vals = (a[1],guid)
			update = "UPDATE %s SET %s = ? WHERE guid = ?"%(table,a[0])
			# print update , vals
			c.execute(update,vals)
		connect.commit()
		c.close()
	def Delete(self,table,guid):
		connect = self.Connect()
		c = connect.cursor()
		# for a in values:
		vals = (guid,)
		update = "DELETE FROM %s WHERE guid = ?"%(table)
		print update , vals
		c.execute(update,vals)
		connect.commit()
		c.close()
	def searchByAll(self,table):
		c = self.Connect().cursor()
		select = "SELECT * FROM %s"%table
		c.execute(select)
		result = c.fetchall()
		c.close()
		# for a in result:
			# print 'searchall : ',a
		return result
	def searchByGuid(self,table,guid):
		c = self.Connect().cursor()
		select = "SELECT * FROM %s where guid='%s'"%(table,guid)
		c.execute(select)
		result = c.fetchall()
		c.close()
		return result
	def searchValueByGuid(self,table,value,guid):
		c = self.Connect().cursor()
		select = "SELECT %s FROM %s where guid='%s'"%(value,table,guid)
		c.execute(select)
		result = c.fetchall()
		c.close()
		return result
	def searchValueByVars(self,table,value,vars):
		c = self.Connect().cursor()
		select = "SELECT %s FROM %s where %s='%s'"%(value,table,vars[0],vars[1])
		c.execute(select)
		result = c.fetchall()
		c.close()
		return result
class bd_client:
	def __init__(self):
		self.bd = bd()
		self.createTables()
	def createTables(self):
		arguments = "guid VARCHAR,name VARCHAR,rights INTEGER,live VARCHAR,dns VARCHAR"
		self.bd.Create("client",arguments)
		arguments = "guid VARCHAR,alias VARCHAR"
		self.bd.Create("alias",arguments)
	def insertClient(self,client):
		if not self.bd.searchByGuid("client",client.guid):
			BDlist = ('guid','name','rights','live','dns')
			values = []
			for a in BDlist:
				values.append(getattr(client,a))
			self.bd.Insert("client",values)
	def updateClient(self,client):
		a = 'rights'
		values = [(a,getattr(client,a))]
		self.bd.Update("client",client.guid,values)
	def searchAllclients(self):
		return self.bd.searchByAll("client")
	def searchClientByGuid(self, guid):
		return self.bd.searchByGuid("client",guid)
	def checkAlias(self,name,guid):
		client = self.bd.searchByGuid("alias",guid)
		for c in client:
			if name == c['alias'] :
				return
		if name :
			self.bd.Insert("alias",[guid,name])
class bd_admin:
	def __init__(self):
		self.bd = bd()
	def getAlias(self,guid):
		result = self.bd.searchByGuid("alias",guid)
		alias = []
		for a in result:
			alias.append(a['alias'])
		return alias
	def setlevel(self,guid,name,rights):
		values = [('rights',rights),('alias',name)]
		self.bd.Update("client",guid,values)
class bd_ban:
	def __init__(self):
		self.bd = bd()
		self.createTables()
	def createTables(self):
		values = "guid VARCHAR,ip INTEGER,nameban VARCHAR,dateban INTEGER,timeban INTEGER,admin VARCHAR,argu VARCHAR"
		self.bd.Create("banlist",values)
	def insertBan(self,guid,ip,name,banTime,Admin,arguments):
		date = kiwi.getTime()
		ip = self.parseIp(ip)
		values = guid,ip,name,date,banTime,Admin,arguments
		self.bd.Insert("banlist",values)
	# def updateBan(self,client):
		# BDlist = ('id','name','guid','timestamp','timeban','ip','admin')
		# c = self.connect.cursor()
		# for a in BDlist:
			# insert = "update banlist set %s='%s' where guid='%s'"%(a,getattr(client,a),client.guid)
			# c.execute(insert)
		# self.connect.commit()
		# c.close()
	def removeBan(self,guid):
		self.bd.Delete("banlist",guid)
	def searchAll(self):
		return self.bd.searchByAll('banlist')
	def searchByGuid(self, guid):
		return self.bd.searchByGuid('banlist',guid)
	def searchByIp(self, ip):
		return self.bd.searchValueByVars('banlist','*',['ip',ip])
	def searchByName(self, name):
		return self.bd.searchValueByVars('banlist','*',['name',name])
	def parseIp(self, ip):
		ip = ip.split('.')
		d = ''
		for a in ip:
			if len(a) == 3:
				pass
			elif len(a) == 2:
				a='0'+a
			elif len(a) == 1:
				a='00'+a
			d+=a
		return d
class bd_welcome:
	def __init__(self):
		self.bd = bd()
		self.createTables()
	def createTables(self):
		arguments = "guid VARCHAR, id INTEGER"
		self.bd.Create("welcome",arguments)
	def insertId(self, guid):
		values = [guid,1]
		self.bd.Insert("welcome",values)
	def updateId(self, guid, id):
		values = [('id',id)]
		self.bd.Update("welcome",guid,values)
	def checkClient(self, guid):
		result = self.bd.searchValueByGuid("welcome","id",guid)
		if result:
			return result[0]['id']
		return False
class bd_pub:
	def __init__(self):
		self.bd = bd()
		self.createTables()
	def createTables(self):
		arguments = "guid VARCHAR, note VARCHAR(100), date VARCHAR, etat INTEGER"
		self.bd.Create("pub",arguments)
		result = self.bd.searchByGuid("pub","0")
		if not result :
			self.bd.Insert("pub",['0','date', '0', 1])
			self.bd.Insert("pub",['0','^4Tapez ^2!help ^4 pour voir la liste des commandes.', '0', 1])
			self.bd.Insert("pub",['0','^2KIWI V3 ^4est a votre disposition.', '0', 1])
	def insertNote(self, guid, note, date):
		value = [guid,note,date,3]
		self.bd.Insert("pub",value)
	def updateNote(self, note, etat):
		connect = self.bd.Connect()
		c = connect.cursor()
		vals = (etat,note)
		update = "UPDATE pub SET etat = ? WHERE note = ?"
		c.execute(update,vals)
		connect.commit()
		c.close()
	def checkNotes(self):
		value = "*"
		vars = ["etat",1]
		notes = self.bd.searchValueByVars("pub",value,vars)
		return notes
	def checkNewNotes(self):
		value = "note"
		vars = ["etat",3]
		notes = self.bd.searchValueByVars("pub",value,vars)
		# print notes
		return notes
	def checkName(self, guid):
		value = "name"
		vars = ["guid",guid]
		result = self.bd.searchValueByVars("client",value,vars)
		# print result
		return result
